<template>
  <div class="flex items-center gap-2">
    <select
      v-model="currentLocale"
      @change="handleLanguageChange"
      class="px-3 py-2 border border-gray-300 rounded-md bg-white cursor-pointer text-sm transition-all duration-300 min-w-[120px] hover:border-primary-500 hover:shadow-md focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-200"
      :aria-label="$t('switchLanguage')"
    >
      <option
        v-for="locale in availableLocales"
        :key="locale.code"
        :value="locale.code"
      >
        {{ locale.flag ? `${locale.flag} ${locale.name}` : locale.name }}
      </option>
    </select>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { SUPPORTED_LANGUAGES } from '../../../i18n/config/languages'

// 使用 Nuxt i18n 提供的 composable
const { locale, setLocale } = useI18n()

// 获取支持的语言列表（从配置文件导入）
const availableLocales = SUPPORTED_LANGUAGES.map(lang => ({
  code: lang.code,
  name: lang.nativeName,
  flag: lang.flag
}))

// 当前语言状态，直接绑定到 i18n 的 locale
const currentLocale = ref(locale.value)

// 监听 locale 变化
watch(locale, (newLocale) => {
  currentLocale.value = newLocale
  // 更新 HTML dir 属性以支持 RTL
  updateDocumentDirection(newLocale)
})

// 组件挂载时初始化
onMounted(() => {
  currentLocale.value = locale.value
  updateDocumentDirection(locale.value)
})

// 处理语言切换
const handleLanguageChange = async () => {
  try {
    await setLocale(currentLocale.value)
    console.log('语言已切换到:', currentLocale.value)
  } catch (error) {
    console.error('语言切换失败:', error)
  }
}

// 更新文档方向（RTL支持）
const updateDocumentDirection = (languageCode) => {
  if (typeof document !== 'undefined') {
    const isRTL = languageCode === 'ar-SA'
    document.documentElement.dir = isRTL ? 'rtl' : 'ltr'
    document.documentElement.lang = languageCode
  }
}
</script>

